const fs = require('fs-extra');
const path = require('path');
const axios = require('axios');

async function downloadImages(fileName) {
  try {
    // 读取文件内容
    const filePath = path.resolve(__dirname, fileName);
    const fileContent = await fs.readFile(filePath, 'utf-8');

    // 正则提取 URL
    const regex = /https:\/\/cos\.brandgo\.cn\/svg\/.*?\.png/g;
    const urls = fileContent.match(regex);

    if (!urls) {
      console.log('未找到符合条件的 URL。');
      return;
    }

    // 创建下载目录
    const downloadDir = path.join(path.dirname(filePath), 'downloads');
    await fs.ensureDir(downloadDir);

    // 下载每个图片
    for (const url of urls) {
      const fileName = path.basename(url);
      const filePath = path.join(downloadDir, fileName);

      const response = await axios.get(url, { responseType: 'stream' });
      response.data.pipe(fs.createWriteStream(filePath));

      response.data.on('end', () => {
        console.log(`下载完成: ${filePath}`);
      });

      response.data.on('error', (err) => {
        console.error(`下载出错: ${err.message}`);
      });
    }
  } catch (error) {
    console.error(`发生错误: ${error.message}`);
  }
}

const homePath = path.join(__dirname, '../../projects/hand-account', 'home.pug')
// 使用示例
downloadImages(homePath); // 将 'your-file.txt' 替换为您要读取的文件名
